﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text.RegularExpressions;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// “空白页”项模板在 http://go.microsoft.com/fwlink/?LinkId=234238 上有介绍

namespace LikeBangumi.Pages
{
    /// <summary>
    /// 可用于自身或导航至 Frame 内部的空白页。
    /// </summary>
    public sealed partial class DiliInfo : Page
    {
        public delegate void PlayVideo(PlayModel model);
        public event PlayVideo playEvent;
        public DiliInfo()
        {
            this.InitializeComponent();
            NavigationCacheMode = NavigationCacheMode.Required;
        }
        MyBangumi mo = new MyBangumi();
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            //
            mo.Info = e.Parameter as string;
            GetISAtt(mo.Info);
            mo.Type = 2;
            
            GetList(e.Parameter as string);
        }
        private void GetISAtt(string info)
        {
            using (var conn = AppDatabase.GetDbConnection())
            {
                // 受影响行数。
                var m = from p in conn.Table<MyBangumi>()
                        where p.Info == info
                        select p;
                if (m.ToList().Count == 0)
                {
                    btn_AddZuiFan.IsEnabled = true;
                }
                else
                {
                    btn_AddZuiFan.IsEnabled = false;
                }
            }
        }
        private void list_Video_ItemClick(object sender, ItemClickEventArgs e)
        {
            DModel model = e.ClickedItem as DModel;
            playEvent(new PlayModel() { type = BangumiType.Dilidili, info = model.url });
            //this.Frame.Navigate(typeof(TestPlayerPage), (e.ClickedItem as DModel).url);
        }
        WebClientClass wc;
        private async void GetList(string name)
        {
            try
            {
                pr_Load.Visibility = Visibility.Visible;
                wc = new WebClientClass();
            
                string results = await wc.GetResultsUTF8Encode(new Uri(name));
                DModel info = new DModel();
                info.title = Regex.Match(results, @"<h1>(.*?)</h1>").Groups[1].Value;
                info.img = Regex.Match(results, @"<dt><img src=""(.*?)""/></dt>").Groups[1].Value;
                info.area = Regex.Match(results, @"<b>地区：</b><a.*?>(.*?)</a>").Groups[1].Value;
                info.date= Regex.Match(results, @"<b>年代：</b><a.*?>(.*?)</a>").Groups[1].Value;
                info.tag = Regex.Match(results, @"<b>标签：</b>(.*?)</div>").Groups[1].Value;
                info.status = Regex.Match(results, @"<b>状态：</b>(.*?)</div>").Groups[1].Value;
                info.desc = Regex.Match(results, @"<b>简介：</b>(.*?)</div></p>").Groups[1].Value;
                BanSeason_Grid.DataContext = info;
                mo.Img = info.img;
                mo.Title = info.title;
               
                MatchCollection mc = Regex.Matches(results, @"<li><a href=""(.*?)"" target=""_self""><em><span>(.*?)</span>(.*?)</em></a></li>", RegexOptions.Multiline);
                List<DModel> listModel = new List<DModel>();
                foreach (Match item in mc)
                {
                    listModel.Add(new DModel()
                    {
                        url = item.Groups[1].Value,
                        num = item.Groups[2].Value,
                        desc = item.Groups[3].Value
                    });
                }
                if (listModel.Count!=0)
                {
                    mo.New = listModel[listModel.Count - 1].num;
                }
                list_Video.ItemsSource = listModel;
            }
            catch (Exception)
            {
                messShow.Show("读取失败", 3000);
            }
            finally
            {
                pr_Load.Visibility = Visibility.Collapsed;
            }

        }

        private void btn_AddZuiFan_Click(object sender, RoutedEventArgs e)
        {
            using (var conn = AppDatabase.GetDbConnection())
            {
                // 受影响行数。
                var count = conn.Insert(mo);
                if (count == 1)
                {
                    messShow.Show("已经添加到我的追番", 3000);
                    btn_AddZuiFan.IsEnabled = false;
                }
                else
                {
                    messShow.Show("添加失败", 3000);
                }
            }
        }


        private async void btn_OK_Click(object sender, RoutedEventArgs e)
        {
            using (DownHelper wc = new DownHelper())
            {
                if (list_Video.SelectedItems.Count != 0)
                {
                    //循环读取全部选中的项目
                    foreach (DModel item in list_Video.SelectedItems)
                    {
                        string Downurl = await wc.GetVideoDiliUri(item.url);//取得视频URL
                        if (Downurl != null)
                        {
                            DownHelper.DownModel model = new DownHelper.DownModel()
                            {
                                title = "【番剧】" + mo.Title,
                                part = item.num,
                                url = Downurl,
                                aid = mo.Info,
                                downloaded = false,
                                partTitle = item.desc ?? "",
                                isBangumi = true
                            };
                            wc.StartDownloadDili(model);
                            //StartDownload(model);
                        }
                        else
                        {
                            MessageDialog md = new MessageDialog(item.title + "\t视频地址获取失败");
                            await md.ShowAsync();
                        }
                    }
                    messShow.Show("任务已加入下载队列", 3000);
                    list_Video.SelectionMode = ListViewSelectionMode.None;
                    list_Video.IsItemClickEnabled = true;
                    com_bar_Down.Visibility = Visibility.Collapsed;
                    com_bar.Visibility = Visibility.Visible;
                }
                else
                {
                    list_Video.SelectionMode = ListViewSelectionMode.None;
                    list_Video.IsItemClickEnabled = true;
                    com_bar_Down.Visibility = Visibility.Collapsed;
                    com_bar.Visibility = Visibility.Visible;
                }
            }

        }

        private void btn_Cancel_Click(object sender, RoutedEventArgs e)
        {
            com_bar.Visibility = Visibility.Visible;
            com_bar_Down.Visibility = Visibility.Collapsed;
            list_Video.SelectionMode = ListViewSelectionMode.None;
            list_Video.IsItemClickEnabled = true;
        }

        private void btn_Down_Click(object sender, RoutedEventArgs e)
        {
            com_bar.Visibility = Visibility.Collapsed;
            com_bar_Down.Visibility = Visibility.Visible;
            list_Video.SelectionMode = ListViewSelectionMode.Multiple;
            list_Video.IsItemClickEnabled = false;
        }


    }
    public class DModel
    {
        public string url { get; set; }
        public string num { get; set; }
        public string desc { get; set; }

        public string title { get; set; }
        public string img { get; set; }
        public string area { get; set; }
        public string date { get; set; }
        public string tag { get; set; }
        public string status { get; set; }
        //public string desc { }
    }

}
